//
//  ClubGameInfoViewController.swift
//  77Club
//
//  Created by Apple on 2024/11/5.
//

import UIKit
import JXSegmentedView

class ClubGameInfoViewController: ClubBaseViewController {

    private var topView = ClubGameInfoTopView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.rowHeight = 78.0.Scale
        tableView.register(ClubGameInfoCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        return tableView
    }()
    

    private var dataSource: [ClubGameCommunityListModel]?
    private var pageIndex = 1
    private var sortby = "1"
    //"92"
    var communityId: String = ""{
        didSet{
            loadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            topView
            tableView
        }
        
        topView.leading(0).trailing(0).top(0).height(44.0.Scale)
        tableView.leading(0).trailing(0).bottom(0)
        tableView.Top == topView.Bottom
        
        topView.updateDataBlock = { type in
            self.sortby = type
            self.loadNewData()
        }
        
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
    }

}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubGameInfoViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return dataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameInfoCell", for: indexPath) as! ClubGameInfoCell
        cell.model = dataSource?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if let model = dataSource?[indexPath.row] {
            if model.type == "1" {
                let webView = ClubWebViewController()
                var urlStr = model.webview_url
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                    urlStr = urlStr + "&uid=\(uid)"
                }
                urlStr = urlStr + "&model=ios"
                webView.urlString = urlStr
                webView.titleName = "资讯详情"
                webView.ishiddenNav = true
                self.navigationController?.pushViewController(webView, animated: true)
            }else{
                let detailVC = ClubForumDetailViewController()
                detailVC.newId = model.id
                self.navigationController?.pushViewController(detailVC, animated: true)
            }
        }
    }

}

//MARK: Data
extension ClubGameInfoViewController {

    private func loadData(){
        ToastUtil.show()
        Task {
            let res = await network.request(.communityPostList(communityID: communityId, type: "", sortby: sortby, page: pageIndex),type: ClubGameCommunityListModel.self)
            tableView.refresh_end()
            ToastUtil.dismiss()
            if res.isSuccess, let models = res.models {
                self.dataSource = models
                tableView.reloadData()
            }
        }
    }
    
    @objc private func loadNewData(){
        pageIndex = 1
        loadData()
    }
    
    @objc private func loadMoreData(){
        pageIndex += 1
        Task {
            let res = await network.request(.communityPostList(communityID: communityId, type: "", sortby: sortby, page: pageIndex),type: ClubGameCommunityListModel.self)
            tableView.refresh_end()
            ToastUtil.dismiss()
            if res.isSuccess, let models = res.models {
                self.dataSource?.append(contentsOf: models)
                tableView.reloadData()
            }
        }
    }
}

extension ClubGameInfoViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

class ClubGameInfoTopView: UIView {
    
    private let sortButton = c_make_ex(UIButton.self)
        .image("GameDetail_sortNor").image("GameDetail_sortSel", state: .selected).end()
    
    var updateDataBlock: ((_: String) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = "#F7F8FA".toColor
        
        subviews{
            sortButton
        }
        
        sortButton.trailing(12.0.Scale).width(76.0.Scale).height(28.0.Scale).centerVertically()
        sortButton.addTarget(self, action: #selector(clickSortButton), for: .touchUpInside)
    }
    
    @objc private func clickSortButton(){

        sortButton.isSelected = !sortButton.isSelected
        let sortType = sortButton.isSelected ? "0" : "1"
        updateDataBlock?(sortType)
    }
 
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}


class ClubGameInfoCell: UITableViewCell {

    var iconImageView = UIImageView()
    private let shadowView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.1)).end()
    var nameLabel = UILabel()
    var timeLabel = UILabel()
    private let dianLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(11.font_medium).text("·")
        .alignment(.center).end()
    private let lookButton = UIIconButton(style: .leading(itemSpace: 2))
    private let commitButton = UIIconButton(style: .leading(itemSpace: 2))
    
    var model: ClubGameCommunityListModel?{
        didSet {
            guard let md = model else { return }

            if md.image.count > 0 {
                let url = md.image[0]
                iconImageView.loadImage(url: url)
            }
            // 插入图片到指定位置
            nameLabel.text = md.title
            timeLabel.text = ClubGlobalTool.shared.timeDescription(from: md.time)
            if md.look == "0" {
                lookButton.setTitle("浏览", for: .normal)
            }else{
                lookButton.setTitle(md.look + "浏览", for: .normal)
            }
            if md.pinglun == "0" {
                commitButton.setTitle("评论", for: .normal)
            }else{
                commitButton.setTitle(md.pinglun + "评论", for: .normal)
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.addSubview(iconImageView)
        iconImageView.addSubview(shadowView)
        contentView.addSubview(nameLabel)
        contentView.addSubview(timeLabel)
        contentView.addSubview(dianLabel)
        contentView.addSubview(lookButton)
        contentView.addSubview(commitButton)
        
        iconImageView.layer.cornerRadius = 8
        iconImageView.layer.masksToBounds = true
        iconImageView.contentMode = .scaleAspectFill

        nameLabel.font = 16.font_medium
        nameLabel.textColor = "#2E3033".toColor
        nameLabel.numberOfLines = 2
        
        timeLabel.font = 12.font_medium
        timeLabel.textColor = "#AEB0B3".toColor
        
        lookButton.style { v in
            v.iconSize = CGSize(width: 12.0.Scale, height: 12.0.Scale)
            v.setImage("Info_smallLook".toImage, for: .normal)
            v.setTitleColor("#AEB0B3".toColor, for: .normal)
            v.titleLabel?.font = 12.font_medium
            v.isUserInteractionEnabled = false
        }
        
        commitButton.style { v in
            v.iconSize = CGSize(width: 12.0.Scale, height: 12.0.Scale)
            v.setImage("Info_smallCommit".toImage, for: .normal)
            v.setTitleColor("#AEB0B3".toColor, for: .normal)
            v.titleLabel?.font = 12.font_medium
            v.isUserInteractionEnabled = false
        }
        
        iconImageView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12.0.Scale)
            make.top.equalToSuperview().offset(8.0.Scale)
            make.width.equalTo(120.0.Scale)
            make.height.equalTo(62.0.Scale)
        }
        
        shadowView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        nameLabel.snp.makeConstraints { make in
            make.leading.equalTo(iconImageView.snp.trailing).offset(12.0.Scale)
            make.trailing.equalToSuperview().offset(-12.0.Scale)
            make.top.equalTo(iconImageView)
        }
        
        timeLabel.snp.makeConstraints { make in
            make.leading.equalTo(iconImageView.snp.trailing).offset(12.0.Scale)
            make.trailing.equalToSuperview().offset(-130.0.Scale)
            make.bottom.equalTo(iconImageView)
        }
        
        commitButton.snp.makeConstraints { make in
            make.height.equalTo(12.0.Scale)
            make.trailing.equalToSuperview().offset(-16.0.Scale)
            make.centerY.equalTo(timeLabel)
        }
        
        dianLabel.snp.makeConstraints { make in
            make.trailing.equalTo(commitButton.snp.leading)
            make.centerY.equalTo(commitButton)
        }
        
        lookButton.snp.makeConstraints { make in
            make.height.equalTo(12.0.Scale)
            make.trailing.equalTo(commitButton.snp.leading).offset(-25)
            make.centerY.equalTo(timeLabel)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

